class Solution {

    public int minPathSum(int[][] grid) {
//        return this.walk(0, 0, grid);

        return uniquePaths(grid);

    }

    public int uniquePaths(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 && j == 0){
                    continue;
                }else if (i == 0){
                    grid[i][j] = grid[i][j] + grid[i][j-1];
                }else if (j == 0){
                    grid[i][j] = grid[i][j] + grid[i-1][j];
                }else{
                    grid[i][j] = grid[i][j] + Math.min(grid[i-1][j], grid[i][j-1]);
                }
            }
        }
        return grid[grid.length-1][grid[0].length-1];
    }

    public int walk(int m, int n, int[][] grid) {
        int maxX = grid.length-1, maxY = grid[0].length-1;
        if (m == maxX && n == maxY) {
            return grid[m][n];
        }
        if (m > maxX || n > maxY) {
            return Integer.MAX_VALUE;
        }
        return grid[m][n]+Math.min(this.walk(m+1, n, grid), this.walk(m, n+1, grid));
    }

}
